package com.softstao.guoyu.ui.activity.agent;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.flyco.tablayout.SegmentTabLayout;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.softstao.guoyu.R;
import com.softstao.guoyu.base.BaseActivity;
import com.softstao.guoyu.global.SharePreferenceManager;
import com.softstao.guoyu.model.agent.MonthCondition;
import com.softstao.guoyu.model.agent.MonthDetail;
import com.softstao.guoyu.model.agent.MonthOrder;
import com.softstao.guoyu.model.agent.MonthOrderList;
import com.softstao.guoyu.model.agent.MonthProList;
import com.softstao.guoyu.model.agent.Product;
import com.softstao.guoyu.mvp.interactor.agent.AgentInteractor;
import com.softstao.guoyu.mvp.presenter.agent.AgentPresenter;
import com.softstao.guoyu.mvp.viewer.agent.MonthDetailViewer;
import com.softstao.guoyu.mvp.viewer.agent.MonthOrderViewer;
import com.softstao.guoyu.mvp.viewer.agent.MonthProViewer;
import com.softstao.guoyu.ui.adapter.ProductAdapter;
import com.softstao.guoyu.ui.baseAdapter.RecycleViewBaseAdapter;
import com.softstao.guoyu.ui.baseAdapter.RecycleViewHolder;
import com.softstao.softstaolibrary.library.utils.LZUtils;
import com.softstao.softstaolibrary.library.widget.CustomScrollerView;
import com.softstao.softstaolibrary.library.widget.EmptyLayout;
import com.softstao.softstaolibrary.library.widget.FullyLinearLayoutManager;
import com.softstao.softstaolibrary.library.widget.MarginDecoration2;
import com.wangjie.androidinject.annotation.annotations.mvp.AIPresenter;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by vaikus on 2017/6/30.
 */

public class AboutOrderActivity extends BaseActivity implements MonthDetailViewer, MonthOrderViewer, MonthProViewer {

    @AIPresenter(presenter = AgentPresenter.class, interactor = AgentInteractor.class)
    AgentPresenter presenter;

    @BindView(R.id.month_detail_view)
    TextView monthDetailView;
    @BindView(R.id.month_achievement)
    TextView monthAchievement;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.month_profit)
    TextView monthProfit;
    @BindView(R.id.month_sales)
    TextView monthSales;
    @BindView(R.id.tab_layout)
    SegmentTabLayout tabLayout;
    @BindView(R.id.list_view)
    RecyclerView listView;
    @BindView(R.id.empty_layout)
    EmptyLayout emptyLayout;
    @BindView(R.id.more)
    TextView more;
    @BindView(R.id.scroll_view)
    CustomScrollerView scrollView;
    @BindView(R.id.loading)
    RelativeLayout loading;
    @BindView(R.id.goods_list)
    RecyclerView goodsList;
    private String type;
    private String[] mTitles = new String[]{"订单", "产品"};
    private Calendar calendar = Calendar.getInstance();
    private int year, month, id, agent_id, method;
    private MonthDetail monthDetail;
    private MonthCondition condition = new MonthCondition();
    private List<Product> productList = new ArrayList<>();
    private List<MonthOrder> orderList = new ArrayList<>();
    private RecycleViewBaseAdapter<MonthOrder> orderAdapter;
    private ProductAdapter productAdapter;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public int _ContentView() {
        return R.layout.activity_about_order;
    }

    @Override
    public void initView() {
        type = getIntent().getStringExtra("type");
        id = getIntent().getIntExtra("id", 0);
        method = getIntent().getIntExtra("method", 0);
        year = getIntent().getIntExtra("year", 0);
        month = getIntent().getIntExtra("month", 0);
        switch (type) {
            case "order":
                initTitle("相关订单");
                monthDetailView.setText("本月相关业绩");
                agent_id = SharePreferenceManager.getInstance().getAgentId();
                break;
            case "achieve":
                initTitle("TA的业绩");
                monthDetailView.setText("本月业绩");
                agent_id = getIntent().getIntExtra("agent_id", 0);
                break;
            case "user":
                initTitle("我的业绩");
                monthDetailView.setText("本月业绩");
                agent_id = SharePreferenceManager.getInstance().getAgentId();
                break;
        }

        tabLayout.setTabData(mTitles);
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                tabLayout.setCurrentTab(position);
                switch (mTitles[position]) {
                    case "订单":
                        listView.setVisibility(View.VISIBLE);
                        goodsList.setVisibility(View.GONE);
                        currentPage = 1;
                        findMonthOrder();
                        break;
                    case "产品":
                        listView.setVisibility(View.GONE);
                        goodsList.setVisibility(View.VISIBLE);
                        currentPage = 1;
                        findMonthPro();
                        break;
                }
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        if (method == 0) {
            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH) + 1;
        }
        time.setText(year + "年" + month + "月");

        scrollView.setOnScrollChangedListener(this);
        setPtrFrameLayoutEnable();

        productAdapter = new ProductAdapter(productList);
        goodsList.setAdapter(productAdapter);
        goodsList.setLayoutManager(new FullyLinearLayoutManager(this));

        orderAdapter = new RecycleViewBaseAdapter<MonthOrder>(orderList, R.layout.layout_order_list_item) {
            @Override
            public void convert(RecycleViewHolder holder, MonthOrder monthOrder) {
                RecyclerView.LayoutParams layoutParams = new RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                holder.itemView.setLayoutParams(layoutParams);
                holder.getView(R.id.right).setVisibility(View.GONE);
                holder.getView(R.id.bottom).setVisibility(View.GONE);
                holder.getView(R.id.source_sn).setVisibility(View.VISIBLE);
                holder.getView(R.id.addr_name).setVisibility(View.VISIBLE);
                holder.setText(R.id.time, "时间：" + format.format(new Date(monthOrder.getDate())))
                        .setText(R.id.from_agent, "下级代理：" + monthOrder.getSubAgentName())
                        .setText(R.id.total_price, getResources().getString(R.string.rmb) + LZUtils.priceFormat(monthOrder.getAmount()))
                        .setText(R.id.order_sn, "订单编号：" + monthOrder.getOrderCode())
                        .setText(R.id.source_sn, "源订单号：" + monthOrder.getSourceCode())
                        .setText(R.id.addr_name, "收货人：" + monthOrder.getAddrName());
                RecyclerView recyclerView = holder.getView(R.id.list_view);
                ProductAdapter adapter;
                if (monthOrder.getProductList()==null){
                    adapter = new ProductAdapter(new ArrayList<Product>());
                }else {
                    adapter = new ProductAdapter(monthOrder.getProductList());
                }
                adapter.setListener(position -> {
                    Intent intent = new Intent(context, AboutOrderDetailActivity.class);
                    intent.putExtra("agent_id",agent_id);
                    intent.putExtra("order_code", monthOrder.getOrderCode());
                    startActivity(intent);
                });
                recyclerView.setTag(adapter);
                recyclerView.setAdapter(adapter);
                recyclerView.setLayoutManager(new FullyLinearLayoutManager(holder.itemView.getContext()));
            }
        };
        orderAdapter.setListener(position -> {
            Intent intent = new Intent(context, AboutOrderDetailActivity.class);
            intent.putExtra("agent_id",agent_id);
            intent.putExtra("order_code", orderList.get(position).getOrderCode());
            startActivity(intent);
        });
        listView.setAdapter(orderAdapter);
        listView.setLayoutManager(new FullyLinearLayoutManager(this));
        listView.addItemDecoration(new MarginDecoration2(this));
    }

    private void initData() {
        monthAchievement.setText(LZUtils.priceFormat(monthDetail.getMonthAchievement()) + "元");
        if (type.equals("user")||type.equals("achieve")){
            monthProfit.setText("本月纯利润：" + LZUtils.priceFormat(monthDetail.getMonthProfit()) + "元");
            monthSales.setText("本月销售量：" + monthDetail.getMonthSalesVolume() + "台");
        }else {
            monthProfit.setText("相关利润：" + LZUtils.priceFormat(monthDetail.getMonthProfit()) + "元");
            monthSales.setText("相关销售量：" + monthDetail.getMonthSalesVolume() + "台");
        }
    }

    @OnClick({R.id.left, R.id.right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left:
                month--;
                if (month < 1) {
                    year--;
                    month = 12;
                }
                time.setText(year + "年" + month + "月");
                findMonthDetail();
                currentPage = 1;
                findMonthOrder();
                findMonthPro();
                break;
            case R.id.right:
                month++;
                if (month > 12) {
                    year++;
                    month = 1;
                }
                time.setText(year + "年" + month + "月");
                findMonthDetail();
                currentPage = 1;
                findMonthOrder();
                findMonthPro();
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        findMonthDetail();
        findMonthOrder();
    }

    @Override
    public void onRefresh() {
        super.onRefresh();
        findMonthDetail();
        findMonthOrder();
        findMonthPro();
    }

    @Override
    public void onLoad() {
        super.onLoad();
        findMonthOrder();
        findMonthPro();
    }

    @Override
    public void findMonthDetail() {
        loading.setVisibility(View.VISIBLE);
        if (id==0) {
            presenter.getMonthDetail(agent_id, "", time.getText().toString().replace("年", "-").replace("月", ""));
        }else {
            presenter.getMonthDetail(agent_id, String.valueOf(id), time.getText().toString().replace("年", "-").replace("月", ""));
        }
    }

    @Override
    public void getMonthDetail(MonthDetail monthDetail) {
        loading.setVisibility(View.GONE);
        if (monthDetail != null) {
            this.monthDetail = monthDetail;
            initData();
        }
    }

    @Override
    public void findMonthPro() {
        loading.setVisibility(View.VISIBLE);
        condition.setAgentId(agent_id);
        if (id==0) {
            condition.setSubAgentId(null);
        }else {
            condition.setSubAgentId(String.valueOf(id));
        }
        condition.setMonth(time.getText().toString().replace("年", "-").replace("月", ""));
        presenter.getMonthPro(currentPage, condition);
    }

    @Override
    public void getMonthProList(MonthProList monthProList) {
        loading.setVisibility(View.GONE);
        if (monthProList != null) {
            if (monthProList.getProductList() != null && monthProList.getProductList().size() != 0) {
                emptyLayout.setVisibility(View.GONE);
                more.setVisibility(View.GONE);
                if (currentPage == 1) {
                    productList.clear();
                }
                productList.addAll(monthProList.getProductList());
                productAdapter.notifyDataSetChanged();
            } else {
                if (currentPage == 1) {
                    productList.clear();
                    productAdapter.notifyDataSetChanged();
                    emptyLayout.setVisibility(View.VISIBLE);
                } else {
                    more.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @Override
    public void findMonthOrder() {
        loading.setVisibility(View.VISIBLE);
        condition.setAgentId(agent_id);
        if (id==0) {
            condition.setSubAgentId(null);
        }else {
            condition.setSubAgentId(String.valueOf(id));
        }
        condition.setMonth(time.getText().toString().replace("年", "-").replace("月", ""));
        presenter.getMonthOrder(currentPage, condition);
    }

    @Override
    public void getMonthOrderList(MonthOrderList monthOrderList) {
        loading.setVisibility(View.GONE);
        if (monthOrderList != null) {
            if (monthOrderList.getOrderList() != null && monthOrderList.getOrderList().size() != 0) {
                emptyLayout.setVisibility(View.GONE);
                more.setVisibility(View.GONE);
                if (currentPage == 1) {
                    orderList.clear();
                }
                orderList.addAll(monthOrderList.getOrderList());
                orderAdapter.notifyDataSetChanged();
            } else {
                if (currentPage == 1) {
                    orderList.clear();
                    orderAdapter.notifyDataSetChanged();
                    emptyLayout.setVisibility(View.VISIBLE);
                } else {
                    more.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @Override
    protected void error(String msg) {
        super.error(msg);
        loading.setVisibility(View.GONE);
    }
}
